package pers.zb.center.web.boss.controller.message_wall;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.zb.center.common.core.enums.Status;
import pers.zb.center.common.core.vo.AjaxResult;
import pers.zb.center.service.user.api.basic.BasicMessageWallService;
import pers.zb.center.service.user.api.user.UserService;
import pers.zb.center.service.user.entity.basic.BasicMessageWall;
import pers.zb.center.service.user.entity.sys.SysUser;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 
 * 留言墙
 *
 */
@Controller
@RequestMapping("/message/wall")
public class MessageWallController {
    
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private BasicMessageWallService basicMessageWallService;

    @Autowired
    private UserService userService;

    /**
     * 进入留言墙页面
     */
    @RequestMapping("/view")
    @RequiresPermissions("publish:message:view")
    public String toChatView(ModelMap map) {
        int num = 50;
        //获取指定数量的留言列表
        List<BasicMessageWall> messageList = basicMessageWallService.getMessageList(num);
        map.put("messageList",messageList);
        return "/msg_wall/view";
    }

    /**
     * 新增留言消息
     * @param request
     * @param msg
     * @return
     */
    @ResponseBody
    @RequestMapping("/add")
    public AjaxResult<String> addMessage(HttpServletRequest request,BasicMessageWall msg) {
        AjaxResult<String> result = new AjaxResult<String>();
        if(StringUtils.isBlank(msg.getContent()) || "".equals(msg.getContent().replaceAll(" ",""))){
            result.setCode(10001);
            result.setMsg("请输入留言内容");
            return result;
        }
        try {
            msg.setCreateTime(new Date());
            msg.setUpdateTime(new Date());
            msg.setStatus(Status.ENABLE);

            //用户名为空，就指定当前登录的系统用户名
            if(StringUtils.isBlank(msg.getUserName())){
                Subject subject = SecurityUtils.getSubject();
                String userName = String.valueOf(subject.getPrincipal());
                SysUser user =  userService.getUserByName(userName);
                msg.setUserName(userName);
                msg.setUserId(user.getId());
            }
            msg.setIpAddress(getIpAddr(request));
            basicMessageWallService.save(msg);
        } catch (Exception e) {
            result.setCode(10002);
            result.setMsg("留言提交失败，请稍后重试");
            return result;
        }
        return result;
    }


    /**
     * 获取客户端ip
     * @param request
     * @return
     */
    private static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        //这种情况下，是因为客户端使用了localhost访问项目，将localhos换成127.0.0.1就变成了IPV4
        if("0:0:0:0:0:0:0:1".equals(ip)){
            ip = "127.0.0.1";
        }

        return ip;
    }
}
